<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- https://juejin.cn/post/7026896668817621028
    纯js实现图片裁剪工具 -->
    <br>
    <br>
    <input type="file"
        id="inputFile"
        accept="image/*">
    <br>
    <br>
    <div>
        原图大小:
        <div id="size"></div>

        截取后大小:
        <div id="afterSize"></div>
    </div>
    <img id="imgBox"
        src=""
        width="300"
        height="300"
        style="border: 1px solid #ccc;">
    <script>
        inputFile.onchange = () => {
            const file = inputFile.files[0]
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                const imgSrc = reader.result
                handleFile(imgSrc)
            }
        }
        function handleFile(imgSrc) {
            const image = new Image()
            image.src = imgSrc
            image.onload = function () {
                size.innerHTML = `${this.width} x ${this.height}`
                if (this.width === this.height) {
                    console.log('正方形')
                    imgBox.src = imgSrc
                    afterSize.innerHTML = `${this.width} x ${this.height}`
                    return
                }
                const diameter = Math.min(this.width, this.height)
                console.log(diameter)
                afterSize.innerHTML = `${diameter} x ${diameter}`
                const rect = {
                    x: 0,
                    y: 0,
                    width: diameter,
                    height: diameter
                }
                if (this.width > this.height) {
                    rect.x = (this.width - diameter) / 2
                } else {
                    rect.y = (this.height - diameter) / 2
                }
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                const { x, y, width, height } = rect
                canvas.width = width
                canvas.height = height
                ctx.drawImage(this, x, y, width, height, 0, 0, width, height)
                const url = canvas.toDataURL('image/png')
                imgBox.src = url
            }
        }
    </script>
</body>

</html>